extends NodeState


@export var enemy: BasicEnemy


const REMOTE_TARGET_DISTANCE := BasicEnemy.TARGET_DISTANCE * 4.0


var target_slot: EnemySlot

var remote_attack_location: Vector2
var direction: Vector2


func _on_process(_delta : float) -> void:
	enemy.flip_sprite()

	if _changing_state:
		return
	if is_remote_attack():
		move_to_remote_attack_location()
	else:
		var collectible := enemy.try_pickup_collectible()
		if collectible != null:
			transition_state(BasicEnemy.STATE_PICKUP)
			return
		move_to_slot()
	enemy.look_at_player()
	process_animation()



func _on_enter() -> void:
	target_slot = null
	remote_attack_location = Vector2.ZERO
	if is_remote_attack():
		remote_attack_location = enemy.get_remote_attack_location()
	else:
		process_reserve_slot()




func _on_exit() -> void:
	free_slot()



func is_remote_attack() -> bool:
	return enemy.is_flying_knife_attack() or enemy.is_shoot_gun_attack()



func move_to_slot():
	if target_slot == null:
		return
	# 接近到一定距离后转换状态
	if enemy.global_position.distance_squared_to(target_slot.global_position) < BasicEnemy.TARGET_DISTANCE:
		# 应该转换到攻击状态
		transition_state(BasicEnemy.STATE_PUNCH)
		return
	direction = (target_slot.global_position - enemy.global_position).normalized()
	enemy.velocity = direction * enemy.speed
	enemy.move_and_slide()



func move_to_remote_attack_location():
	if remote_attack_location == Vector2.ZERO:
		return
	# 接近到一定距离后转换状态
	if is_reached_remote_attack_location():
		if enemy.projectileAim.is_colliding():
			# 如果射线检测到碰撞，说明可以进行远程攻击
			transition_to_remote_attack()
		else:
			transition_state(BasicEnemy.STATE_IDLE)
		return
	direction = (remote_attack_location - enemy.global_position).normalized()
	enemy.velocity = direction * enemy.speed
	enemy.move_and_slide()




func process_reserve_slot():
	var slot := enemy.player.enemySlots.reserve_slot(enemy)
	if slot == null:
		# 未获得槽位，暂时回到idle
		call_deferred("transition_state", BasicEnemy.STATE_IDLE)
		return
	target_slot = slot


func free_slot():
	enemy.player.enemySlots.free_slot(enemy)


func process_animation():
	enemy.animationPlayer.play(BasicEnemy.ANIMATION_WALK)


# 到达远程攻击点位
func is_reached_remote_attack_location() -> bool:
	var pos = enemy.global_position
	return absf(pos.x - remote_attack_location.x) < 1.0 && absf(pos.y - remote_attack_location.y) < 1.0


# 切换到远程攻击状态
func transition_to_remote_attack():
	if enemy.is_flying_knife_attack():
		transition_state(BasicEnemy.STATE_THROW)
	elif enemy.is_shoot_gun_attack():
		transition_state(BasicEnemy.STATE_SHOOT)
